package myClient.clientCore;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.Data;
import myClient.handler.ExceptionHandler;
import myClient.handler.LoginResponseHandler;
import myClient.sender.ChatSender;
import myClient.sender.LoginSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import protobuf.codec.MyProtobufDecoder;
import protobuf.codec.MyProtobufEncoder;

@Data
@Service("ChatNettyClient")
public class ChatNettyClient {

    @Value("${chat.server.ip}")
    private String host; //服务器 IP
    @Value("${chat.server.port}")
    private int port;  //服务器端口号
    @Autowired
    private LoginResponseHandler loginResponseHandler;  //登录请求处理器
    @Autowired
    private ExceptionHandler exceptionHandler;  //异常处理器

    private Channel channel;
    private ChatSender chatSender;  //发送聊天信息
    private LoginSender loginSender;  //发送登录请求

    private boolean initFlag = true;
    private GenericFutureListener<ChannelFuture> connectedListener;  //监听 连接服务器是否成功
    private Bootstrap bootstrap;
    private EventLoopGroup eventLoopGroup;

    /**
     * 客户端的是 Bootstrap，服务端的则是 ServerBootstrap。
     * 都是 AbstractBootstrap的子类。
     **/
    public ChatNettyClient() {
        //通过 nio方式来接收连接和处理连接
        eventLoopGroup = new NioEventLoopGroup(1);
    }

    /**
     * 连接服务器
     */
    public void connectServer() {
        try {
            bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast("decoder", new MyProtobufDecoder())
                                    .addLast("encoder", new MyProtobufEncoder())
                                    .addLast(loginResponseHandler)
                                    .addLast(exceptionHandler);
                        }
                    });
            System.out.println("客户端开始连接服务器。。。");

            bootstrap.remoteAddress(host, port)
                    .connect()
                    .addListener(connectedListener);
        } catch (Exception e) {
            System.out.println("连接服务器失败！ " + e.getMessage());
        }
    }

}
